-module(middle_auth).

-export([
    enter/1
    ,leave/1
]).

-include("common.hrl").
-include("http.hrl").
-include("error.hrl").
-include("key.hrl").


enter(#{req := Req}) ->
    TokenBin = cowboy_req:header(?KEY_HTTP_HEADER_X_TOKEN, Req),
    ?IF(TokenBin == undefined orelse TokenBin == <<>>, ?RESP_FAILED_ERR(?HTTP_STATUS_FORBIDDEN, ?ERROR_TOKEN_EMPTY), ok),

    Token = util_type:to_integer(TokenBin),
    Id = token:get(Token),
    ?IF(Id == undefined, ?RESP_FAILED_ERR(?HTTP_STATUS_FORBIDDEN, ?ERROR_TOKEN_OUT), ok),

    case model_adm_user:get(Id) of
        {ok, undefined} ->
            ?RESP_FAILED_ERR(?HTTP_STATUS_FORBIDDEN, ?ERROR_TOKEN_NO_USER);
        {ok, AdmUser} ->
            erlang:put(?KEY_ADM_USER, AdmUser),
            erlang:put(?KEY_ADM_USER_ID, Id),
            ok;
        {error, Reason} ->
            ?ERR("MySQL 错误:~s", [Reason]),
            ?RESP_FAILED_ERR(?HTTP_STATUS_INTERNAL_SERVER_ERROR, ?ERROR_DB)
    end.


leave(_Req) ->
    ok.
